<template>
  <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
    <el-form-item label="旧密码" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off" placeholder="请输入旧密码" />
    </el-form-item>

    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="ruleForm.newPassword" type="password" autocomplete="off" placeholder="请输入新密码" />
    </el-form-item>

    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model="ruleForm.confirmPassword" type="password" autocomplete="off" placeholder="请输入确认密码" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submit('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === this.ruleForm.password) {
        callback(new Error('新密码不能与新密码相同！'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.ruleForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        password: [
          { required: true, trigger: 'blur', message: '请输入旧密码' },
          { min: 3, max: 64, message: '长度在 3 到 64 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, trigger: 'blur', message: '请输入新密码' },
          { min: 3, max: 64, message: '长度在 3 到 64 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', message: '请输入确认密码' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          console.log('数据校验失败!!')
          return false
        }
        console.log('数据验证成功')
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
